package list;
// 删除倒数第n个节点
public class leetcode19 {
    public static void main(String[] args) {
        int[] nums = {1};
        int target = 1;
        ListNode head = createListNode(nums);
        printList(head);

        printList(removeNthFromEnd(head, target));
    }

    public  static void printList(ListNode head){
        if(head == null) System.out.println("null");
        while(head != null){
            System.out.print(head.val + " ");
            head = head.next;
        }
        System.out.println();
    }

    private static ListNode createListNode(int[] nums){
        ListNode head = new ListNode(nums[0]);
        ListNode current = head;
        for (int i = 1; i < nums.length; i++) {
            ListNode temp = new ListNode(nums[i]);
            current.next = temp;
            current = current.next;
        }
        return head;
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
//        if(head == null || head.next == null) return null;
        ListNode newhead = new ListNode(0);
        newhead.next = head;
        ListNode fast = newhead;
        ListNode slow = newhead;
        for(int i = 0; i < n; i++){
            fast = fast.next;
        }
        while (fast.next != null){
            fast = fast.next;
            slow = slow.next;
        }

        slow.next = slow.next.next;

        return head.next;
    }
}
